﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace JobList
{
    public partial class FrmMain : Form
    {
        IniFiles ini;
        static Singleton singleton = Singleton._instance;
        public FrmMain()
        {
            InitializeComponent();
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            singleton.FilePath = System.Environment.CurrentDirectory;
            singleton.ConfigIniPath = singleton.FilePath + @"\config.ini";
            singleton.JobListJsonPath = singleton.FilePath + @"\JobList.json";
            singleton.JobListContentPath = singleton.FilePath + @"\内容文件";

            singleton.IsExistDirPath(singleton.JobListContentPath);
            
            ini = new IniFiles(singleton.ConfigIniPath);
            bool isExists = ini.ExistINIFile();
            if (!isExists)
            {
                FileStream IniFile = new FileStream(singleton.ConfigIniPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);                           
            }

            ini.IniWriteValue("Add", "FChangeJobList", "新增页面");
            ini.IniWriteValue("Add", "groupBox1", "新增JobList");
            ini.IniWriteValue("Add", "BtnChange", "新增");
            ini.IniWriteValue("Modify", "FChangeJobList", "修改页面");
            ini.IniWriteValue("Modify", "groupBox1", "修改JobList");
            ini.IniWriteValue("Modify", "BtnChange", "修改");

            #region 按钮控件方法
            this.BtnRefresh.Click += new System.EventHandler(this.BtnRefresh_Click);
            this.BtnAdd.Click += new System.EventHandler(this.BtnAdd_Click);
            this.BtnModify.Click += new System.EventHandler(this.BtnModify_Click);
            this.BtnDelete.Click += new System.EventHandler(this.BtnDelete_Click);
            this.DGVID.CellClick += new DataGridViewCellEventHandler(this.DGVID_CellClick);
            #endregion

            BtnRefresh_Click(null, null);
        }

        private void BtnRefresh_Click(object sender, EventArgs e)
        {
            if (File.Exists(singleton.JobListJsonPath))
            {
                string ScJobLists = string.Empty;
                using (FileStream _file = new FileStream(singleton.JobListJsonPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    int fsLen = (int)_file.Length;
                    byte[] heByte = new byte[fsLen];
                    int r = _file.Read(heByte, 0, heByte.Length);
                    Encoding encoding = Encoding.UTF8;
                    ScJobLists = encoding.GetString(heByte);
                }

                singleton.cJobLists = JsonConvert.DeserializeObject<List<CJobList>>(ScJobLists);

                if (singleton.cJobLists == null)
                {
                    singleton.cJobLists = new List<CJobList>();
                    CJobList cJobList = new CJobList
                    {
                        ID = Guid.NewGuid().ToString("N"),
                        CreateTime = DateTime.Now,
                        ModifyTime = DateTime.Now,
                        Proposer = "示例1提出者",
                        Executor = "示例1执行者",
                        Title = "示例1标题",
                        Content = "",
                        State = "示例1状态",
                    };
                    singleton.cJobLists.Add(cJobList);

                    cJobList = new CJobList
                    {
                        ID = Guid.NewGuid().ToString("N"),
                        CreateTime = DateTime.Now,
                        ModifyTime = DateTime.Now,
                        Proposer = "示例2提出者",
                        Executor = "示例2执行者",
                        Title = "示例2标题",
                        Content = "",
                        State = "示例2状态",
                    };
                    singleton.cJobLists.Add(cJobList);
                    singleton.SavecJobLists();
                }

                ReLoadDGVID();
                ReLoadLVList(singleton.cJobLists.FirstOrDefault());
                ReLoadRTxtContent(singleton.cJobLists.FirstOrDefault().Content);
                singleton.ActiveCJobListID = singleton.cJobLists.FirstOrDefault().ID;
            }
            else
            {
                CJobList cJobList = new CJobList
                {
                    ID = Guid.NewGuid().ToString("N"),
                    CreateTime = DateTime.Now,
                    ModifyTime = DateTime.Now,
                    Proposer = "示例1提出者",
                    Executor = "示例1执行者",
                    Title = "示例1标题",
                    Content = "",
                    State = "示例1状态",
                };
                singleton.cJobLists.Add(cJobList);

                cJobList = new CJobList
                {
                    ID = Guid.NewGuid().ToString("N"),
                    CreateTime = DateTime.Now,
                    ModifyTime = DateTime.Now,
                    Proposer = "示例2提出者",
                    Executor = "示例2执行者",
                    Title = "示例2标题",
                    Content = "",
                    State = "示例2状态",
                };
                singleton.cJobLists.Add(cJobList);
                singleton.SavecJobLists();

                ReLoadDGVID();
                ReLoadLVList(singleton.cJobLists.FirstOrDefault());
                ReLoadRTxtContent(singleton.cJobLists.FirstOrDefault().Content);
                singleton.ActiveCJobListID = singleton.cJobLists.FirstOrDefault().ID;
            }
        }

        private void BtnAdd_Click(object sender, EventArgs e)
        {
            singleton.FChangeJobListShowValue = 0;
            FChangeJobList fChangeJobList = new FChangeJobList();
            if(fChangeJobList.ShowDialog() == DialogResult.OK)
            {
                BtnRefresh_Click(null, null);
            }
        }

        private void BtnModify_Click(object sender, EventArgs e)
        {
            singleton.FChangeJobListShowValue = 1;
            FChangeJobList fChangeJobList = new FChangeJobList();
            if (fChangeJobList.ShowDialog() == DialogResult.OK)
            {
                BtnRefresh_Click(null, null);
            }
        }

        private void BtnDelete_Click(object sender, EventArgs e)
        {
            if(!string.IsNullOrEmpty(singleton.ActiveCJobListID) && singleton.cJobLists.Count > 0)
            {
                if(MessageBox.Show($"确定要删除唯一编码为{singleton.ActiveCJobListID}的记录吗？", "系统提示", MessageBoxButtons.OKCancel,MessageBoxIcon.Question) == DialogResult.OK)
                {
                    singleton.cJobLists.RemoveAll((v) => v.ID == singleton.ActiveCJobListID);
                    File.Delete(singleton.JobListJsonPath);
                    singleton.SavecJobLists();
                    MessageBox.Show("删除成功！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    BtnRefresh_Click(null, null);
                }
            }
            else
            {
                MessageBox.Show("请选中需要删除的唯一编码！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }            
        }

        private void ReLoadDGVID()
        {
            DataTable baseDT = new DataTable();
            int ISerialNumber = 0;

            baseDT.Columns.Add("序号", typeof(int));
            baseDT.Columns.Add("唯一编码", typeof(string));

            foreach (var cJobListsItem in singleton.cJobLists)
            {
                ISerialNumber += 1;
                baseDT.Rows.Add(new object[] { ISerialNumber, cJobListsItem.ID });
            }
            DGVID.DataSource = baseDT;
        }
        private void ReLoadLVList(CJobList cJobListsItem)
        {
            if (cJobListsItem == null)
            {
                return;
            }

            LVList.Clear();
            LVList.View = View.Details;
            LVList.FullRowSelect = true;
            LVList.GridLines = true;

            ColumnHeader ch = new ColumnHeader
            {
                Text = "类型",
                Width = 120,
                TextAlign = HorizontalAlignment.Left
            };
            LVList.Columns.Add(ch);
            ch = new ColumnHeader
            {
                Text = "实际数据",
                Width = 200,
                TextAlign = HorizontalAlignment.Left
            };
            LVList.Columns.Add(ch);

            this.LVList.BeginUpdate();
            for (int i = 0; i < 6; i++)
            {
                ListViewItem lvi = new ListViewItem();
                switch (i)
                {
                    case 0:
                        lvi = new ListViewItem
                        {
                            ImageIndex = i,
                            Text = "创建时间"
                        };
                        lvi.SubItems.Add(cJobListsItem.CreateTime.ToString("yyyy-MM-dd hh:mm:ss fff"));
                        LVList.Items.Add(lvi);
                        break;
                    case 1:
                        lvi = new ListViewItem
                        {
                            ImageIndex = i,
                            Text = "修改时间"
                        };
                        lvi.SubItems.Add(cJobListsItem.ModifyTime.ToString("yyyy-MM-dd hh:mm:ss fff"));
                        LVList.Items.Add(lvi);
                        break;
                    case 2:
                        lvi = new ListViewItem
                        {
                            ImageIndex = i,
                            Text = "提出者"
                        };
                        lvi.SubItems.Add(cJobListsItem.Proposer);
                        LVList.Items.Add(lvi);
                        break;
                    case 3:
                        lvi = new ListViewItem
                        {
                            ImageIndex = i,
                            Text = "执行者"
                        };
                        lvi.SubItems.Add(cJobListsItem.Executor);
                        LVList.Items.Add(lvi);
                        break;
                    case 4:
                        lvi = new ListViewItem
                        {
                            ImageIndex = i,
                            Text = "标题"
                        };
                        lvi.SubItems.Add(cJobListsItem.Title);
                        LVList.Items.Add(lvi);
                        break;
                    case 5:
                        lvi = new ListViewItem
                        {
                            ImageIndex = i,
                            Text = "状态"
                        };
                        lvi.SubItems.Add(cJobListsItem.State);
                        LVList.Items.Add(lvi);
                        break;
                }
            }
            this.LVList.EndUpdate();
        }
        private void ReLoadRTxtContent(string FileContent)
        {
            if (string.IsNullOrEmpty(FileContent))
            {
                RTxtContent.Clear();
                return;
            }

            if(File.Exists(FileContent))
            {
                RTxtContent.LoadFile(FileContent, RichTextBoxStreamType.RichText);
            }
            else
            {
                MessageBox.Show($"未找到文件：{FileContent}", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            
        }

        private void DGVID_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.ColumnIndex == -1 || e.RowIndex == -1)
                {
                    return;
                }
                DataGridViewCell cell = this.DGVID.Rows[e.RowIndex].Cells[1];
                if (cell == null || cell.Value.ToString() == "" || cell.Value.ToString() == "0")
                {
                    return;
                }
                string headText = this.DGVID.Columns[1].HeaderText;
                switch (headText)
                {
                    case "唯一编码":
                        if (!string.IsNullOrEmpty(cell.Value.ToString()))
                        {
                            singleton.ActiveCJobListID = cell.Value.ToString();
                            CJobList cJobList = singleton.cJobLists.Find((v) => v.ID == singleton.ActiveCJobListID);
                            ReLoadLVList(cJobList);
                            ReLoadRTxtContent(cJobList.Content);
                        }
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
